package com.xxl.job.executor.jobhandler;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.config.WechatPushConfig;
import com.xxl.job.executor.helper.CaiHongPiHelper;
import com.xxl.job.executor.helper.HolidayHelper;
import com.xxl.job.executor.util.HttpUtil;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Component
public class WechatPushJob {
    private final Logger log = LoggerFactory.getLogger(WechatPushJob.class);

    @Autowired
    WechatPushConfig config;
    @XxlJob("wechatPush")
    public void push(){

        String openId = config.getOpenId();
        String templateId = config.getTemplateId();
        Map<String, Object> params = getParams();
        if(params.containsKey("openId")){
            openId=(String)params.get("openId");
        }
        if(params.containsKey("templateId")){
            templateId=(String)params.get("templateId");
        }

        WxMpInMemoryConfigStorage wxStorage  = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(config.getAppId());
        wxStorage.setSecret(config.getSecret());
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId(templateId)
                .url("http://139.9.47.96:8888/start.html#/section-1/page-1")//点击模版消息要访问的网址
                .build();

        genTemplate(templateMessage);

        try {
            XxlJobHelper.log(templateMessage.toJson());
            XxlJobHelper.log(wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage));
        } catch (Exception e) {
            System.out.println("推送失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private void genTemplate(WxMpTemplateMessage templateMessage) {
        templateMessage.addData(new WxMpTemplateData("lianai",getFromMeetToCurrentDay()+"","#C71585"));
        List<String> strings = CaiHongPiHelper.strSplit(CaiHongPiHelper.getCaiHongPi());
        for (int i = 0; i < strings.size(); i++) {
            templateMessage.addData(new WxMpTemplateData("caiHongPi"+i, strings.get(i),"#C51885"));
        }

        Map<String, Long> holidayMap = holidayHelper.toHoliday();
        Set<Map.Entry<String, Long>> entries = holidayMap.entrySet();
        for (Map.Entry<String, Long> entry : entries) {
            String key = entry.getKey();
            Long value = entry.getValue();
            templateMessage.addData(new WxMpTemplateData(key,String.valueOf(value),"#C51885"));
        }

        long l = holidayHelper.toWeekendDay();
        templateMessage.addData(new WxMpTemplateData("weekendDay",String.valueOf(l),"#C51885"));

    }

    long getFromMeetToCurrentDay(){
        LocalDate curDay = LocalDate.now();
        LocalDate meetDay = LocalDate.parse(config.getMeetDay()) ;
        return ChronoUnit.DAYS.between(meetDay, curDay);
    }



    private Map<String, Object> getParams(){
        HashMap<String, Object> map = new HashMap<>();
        // 获取任务参数
        String param = XxlJobHelper.getJobParam();

        // 解析参数
        String[] params = param.split("&");
        for (String p : params) {
            String[] keyValue = p.split("=");
            if (keyValue.length == 2) {
                String key = keyValue[0];
                String value = keyValue[1];
                map.put(key,value);
            }
        }
        return map;
    }

    @Autowired
    HolidayHelper holidayHelper;
    @XxlJob("updateMonthFileAndMap")
    public void updateMonthFileAndMap(){
        LocalDate now = LocalDate.now();
        Map<String, Object> params = getParams();
        if(params.containsKey("date")){
            now=LocalDate.parse((String)params.get("date"));
        }
        log.info("更新的日期是：{}",now.toString());
        XxlJobHelper.log("更新的日期是：{}",now.toString());
        holidayHelper.updateMonthFileAndMap(now);
    }

    @XxlJob("updateYearFileAndMap")
    public void updateYearFileAndMap(){
        LocalDate now = LocalDate.now();
        Map<String, Object> params = getParams();
        if(params.containsKey("date")){
            now=LocalDate.parse((String)params.get("date"));
        }

        holidayHelper.updateYearFileAndMap(now);
    }

}
